package com.yootk.util;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

public class JPAEntityFactory {
    private static final String PERSISTENCE_UNIT = "YootkJPA" ;
    private static EntityManagerFactory entityManagerFactory ;
    private static ThreadLocal<EntityManager> entityManagerThreadLocal = new ThreadLocal<>() ;
    private JPAEntityFactory(){}
    static {
        reBuildEntityManagerFactory();
    }
    public static EntityManagerFactory getEntityManagerFactory(){
        if (entityManagerFactory ==null){
            reBuildEntityManagerFactory();
        }
        return entityManagerFactory ;
    }
    public static EntityManager getEntityManager(){
        EntityManager entityManager = entityManagerThreadLocal.get() ;
        if (entityManager ==null){
            if (entityManagerFactory == null){
                reBuildEntityManagerFactory();
            }
            entityManager = entityManagerFactory.createEntityManager() ;
            entityManagerThreadLocal.set(entityManager);
        }
        return entityManager ;
    }
    public static void close(){
        EntityManager entityManager = entityManagerThreadLocal.get() ;
        if (entityManager != null){
            entityManager.close();
            entityManagerThreadLocal.remove();
        }
    }
    public static void reBuildEntityManagerFactory(){
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT) ;
    }
}
